package com.liudadan.controller;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("upload")
public class FileController {


    @PostMapping("picture")
    public String upload(@RequestParam String account,
                         @RequestParam String password,
                        @RequestParam("header") MultipartFile image) throws IOException {
        String originalFilename = image.getOriginalFilename();
        System.out.println("originalFilename:" + originalFilename);
        String name = image.getName();
        System.out.println("name:" + name);
        byte[] bytes = image.getBytes();
        System.out.println("bytes:" + bytes.length);
        return "success";

    }


    @Autowired
    private ServletContext servletContext;

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        String realPath = servletContext.getRealPath("/image/111.png");
        FileInputStream fileInputStream = new FileInputStream(realPath);

        response.setHeader("Content-Disposition","attachment;filename=111.png");
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] bytes = new byte[1024 * 10];
        int len = -1;
        while((len = fileInputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
        }
        if(outputStream!=null){
            outputStream.close();
        }
    }

}
